import os
import json
from flask import Flask, render_template, jsonify, request
from smartcard.System import readers
from smartcard.Exceptions import NoCardException
from ndef import URIRecord  # 使用正确的库和类名

app = Flask(__name__)
DATA_DIR = "data"
URLS_FILE = os.path.join(DATA_DIR, "urls.txt")
NFC_DATA_FILE = os.path.join(DATA_DIR, "nfc_data.json")

# 初始化数据目录和文件
if not os.path.exists(DATA_DIR):
    os.makedirs(DATA_DIR)
if not os.path.exists(NFC_DATA_FILE):
    with open(NFC_DATA_FILE, 'w') as f:
        json.dump({}, f)

def get_urls():
    """读取待分配的URL列表"""
    try:
        with open(URLS_FILE, 'r') as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        return []

def save_nfc_data(uid, url):
    """保存标签写入记录"""
    data = {}
    if os.path.exists(NFC_DATA_FILE):
        with open(NFC_DATA_FILE, 'r') as f:
            data = json.load(f)
    data[uid] = url
    with open(NFC_DATA_FILE, 'w') as f:
        json.dump(data, f, indent=2)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/next_url')
def get_next_url():
    """获取下一个待分配的URL"""
    urls = get_urls()
    with open(NFC_DATA_FILE, 'r') as f:
        assigned = json.load(f).values()
    
    for url in urls:
        if url not in assigned:
            return jsonify({
                "url": url,
                "remaining": len(urls) - len(assigned)
            })
    return jsonify({"url": None, "remaining": 0})

@app.route('/write_url', methods=['POST'])
def write_url_to_tag():
    """将URL写入NFC标签"""
    try:
        # 解析请求数据
        req_data = request.get_json()
        target_url = req_data['url']

        # 检测读卡器和标签
        reader = readers()[0]
        conn = reader.createConnection()
        conn.connect()

        # 读取UID
        uid_data, sw1, sw2 = conn.transmit([0xFF, 0xCA, 0x00, 0x00, 0x00])
        if sw1 != 0x90 or sw2 != 0x00:
            return jsonify({"status": "error", "message": "读取UID失败"})